package com.gzp.transaction;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 队列的生产者事务
 * 
 * @author Administrator
 *
 */
public class TestQueueProducer {

	private static final String brokerURL = "tcp://localhost:61616";// 在activemq/conf/activemq.xml中
	private static final String queueName = "queue-hello";

	public static void main(String[] args) throws JMSException {
		ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
		Connection connection = factory.createConnection();
		connection.start();
		/**
		 * 第一个参数表示是否开启事务，如果开启，必须要提交事务，消息才能到mq中。
		 * 第二个参数表示连接者的签收状态。如果第一个参数为true，第二个参数意义不大。
		 */
		Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
		Queue queue = session.createQueue(queueName);
		MessageProducer messageProducer = session.createProducer(queue);
		for (int i = 0; i < 10; i++) {
			TextMessage textMessage = session.createTextMessage();
			textMessage.setText("hello-mq" + i);
			messageProducer.send(textMessage);
		}
		// 提交事务
		session.commit();
		messageProducer.close();
		session.close();
		connection.close();
		System.out.println("消息发送成功！");
	}
}
